#!/bin/bash

ADDRESS="[324:71e:281a:9ed3::ace]"
PORT="8888"
URI="http://tinyproxy.stats"
ACTION="systemctl restart tinyproxy"

status() {
        ./monitor.expect > /dev/null
        if [[ $? == "111" ]]; then
                return 1
        else
                return 0
        fi
}

ping() {
        TMP=/tmp/monitor-bash-file
        rm $TMP &> /dev/null

        curl -s --proxy $ADDRESS:$PORT $URI > $TMP &
        sleep 2
        file=$(cat $TMP | grep acetone)
        
        res=0
        if [[ $file == "" ]]; then
                res=0
        else
                res=1 # success
        fi

        rm $TMP &> /dev/null
        return $res
}


action() {
        $ACTION
        if [[ $? == 0 ]]; then
                echo Restart success
        else
                echo Restart failed
        fi
}

main() {
        cd $(dirname "$0")

        socket
        result=$?
        if [[ $result == 1 ]]; then
                echo Socket works!

                ping
                result=$?
                if [[ $result == 1 ]]; then
                        echo Proxy works!
                else
                        echo Proxy offline...
                        action
                fi

        else
                echo Socket offline...
                action
        fi
        
        kill -9 $$ # Завершение во имя убийства фоновых процессов
}

main